<template>
	<div class="bg">
		<goback title="登录页面"></goback>
		<swiper class="swiper" ref="mySwiper">
			<swiper-slide>
				<div class="index">
					<div class="logo_container">
						<img class="logo" :src="require(`@/assets/images/logo.png`)" alt="">
					</div>
					<div class="context">
						<div>你好! 欢迎来到新世界</div>
						<div>我们诚挚地邀请您来参加我们的网站，祝您有一个好的体验.</div>
					</div>
					<div class="select">
						<button class="left_shadow" @click="goto(2)">注册账号</button>
						<button class="left_shadow" @click="goto(1)">已有账号，去登录</button>
					</div>
				</div>
			</swiper-slide>
			<swiper-slide>
				<div class="card shadow">
					<div class="card_title">登录账号</div>
					<div class="login_container">
						<div class="login_inputs">
							<input placeholder="输入您的手机号或昵称" v-model="login_account" />
							<div class="login_password_container">
								<input :type="hide_type" placeholder="输入您的密码" v-model="login_password"/>
								<img :src="require(`@/assets/icons/${eye_state}.png`)" @click="toggle_eye" alt="">
							</div>
						</div>
						<div class="extra_container">
							<div class="extra_top_container">
								<div>
									<input type="radio" v-model="remember_password" value="true"/>
									记住账号和密码
								</div>
								
							</div>
							<div class="extra_bottom_container">
								<div>
									<input type="radio" v-model="confirm_btn_1" value="true"/>
									我已阅读用户守则
								</div>
							</div>
						</div>
						<div class="login_buttons">
							<button class="left_shadow" @click="toggleVCode">立即登录</button>
							<button class="left_shadow" @click="goto(2)">还没有账号，去注册</button>
						</div>
						<VCode :isShow="isShow" @success="login2" />
					</div>
				</div>
			</swiper-slide>
			<swiper-slide>
				<div class="card shadow">
					<div class="card_title">注册账号</div>
					<div class="login_container">
						<div class="login_inputs">
							<input placeholder="输入您的手机号" v-model="register_telephone" />
							<div class="login_password_container">
								<input :type="hide_type" placeholder="输入您的密码"  v-model="register_password"/>
								<img :src="require(`@/assets/icons/${eye_state}.png`)"  @click="toggle_eye"  alt="">
							</div>
							<div class="login_password_container">
								<input :type="hide_type" placeholder="请再次输入您的密码" v-model="register_confirm_password" />
								<img :src="require(`@/assets/icons/${eye_state}.png`)" @click="toggle_eye"  alt="">
							</div>
							<div class="yzm">
								<input placeholder="输入验证码" v-model="register_yzm" />
								<div class="yzm_right_box">
									<img :src="captchaImage" class="captch">
									<div @click="fetchCaptcha" class="noclear">看不清? 换一张</div>
								</div>
							</div>
						</div>
						<div class="extra_container">
							<div class="extra_bottom_container">
								<div>
									<input type="radio" v-model="confirm_btn_2" value="true"/>
									我已阅读用户守则
								</div>
							</div>
						</div>
						<div class="login_buttons">
							<button class="left_shadow" @click="register">立即注册</button>
							<button class="left_shadow" @click="goto(1)">已有账号，去登录</button>
						</div>

					</div>
				</div>

			</swiper-slide>
		</swiper>

		<copyright></copyright>
	</div>
</template>

<script>
	import CryptoJS from "crypto-js";
	import {
		useStore,
		computed
	} from 'vue';


	export default {
		name: "login",
		components: {
			
		},
		beforeDestroy() {
			// 在组件销毁前卸载Swiper  
			this.$refs.mySwiper.swiperInstance.destroy(true,
				true); // 第二个参数为true会重置swiper到初始状态，第三个参数为true会移除swiper内部的dom元素  
		},
		data() {
			return {
				register_telephone: '',
				register_password: '',
				register_confirm_password: '',
				register_yzm: '',
				captchaImage: null,
				login_account: '',
				login_password: '',
				eye_state: '眼睛',
				hide_type: 'password',
				isShow: false, // 验证码模态框是否出现  
				remember_password:false,
				confirm_btn_1:false,
				confirm_btn_2:false
			}
		},
		computed: {

		},
		mounted() {
			
			if(localStorage.getItem('remember_password') != null){
				this.login_password=CryptoJS.AES.decrypt(localStorage.getItem('remember_password'),"20240426").toString(CryptoJS.enc.Utf8);
			} 
			if(localStorage.getItem('remember_account') != null){
				this.login_account=CryptoJS.AES.decrypt(localStorage.getItem('remember_account'),"20240426").toString(CryptoJS.enc.Utf8)
			}
			
			
		},
		methods: {
			// 调用Vuex的action来获取新的验证码和图片  
			fetchCaptcha() {
				// this.$store.dispatch('fetchCaptcha');
				this.axios.get(`${this.IP}/generate_register_code`)  
				  .then(res => {
				   this.captchaImage = this.convertToImage(res.data)
				
				})  
				.catch(error => {  
				  console.error(error);   
				});
			},
			register() {
				if(this.confirm_btn_2==false){
					this.$toast.showMessage("请先勾选愿意遵守用户协议~");
					return;
				}
				

				if(this.register_telephone.trim()==''){
					this.$toast.showMessage("请填写您的注册手机号~");
					return;
				}
				if(this.register_telephone.trim().length!=11){
					this.$toast.showMessage("请填写正确的11位大陆手机号~");
					return;
				}
				if(this.register_password.trim()==''){
					this.$toast.showMessage("请填写您的注册密码~");
					return;
				}
				if(this.register_confirm_password.trim()==''){
					this.$toast.showMessage("请填写二次确认密码~");
					return;
				}
				
				if(this.register_confirm_password != this.register_password){
					this.$toast.showMessage("两次密码不一致,请检查~");
					return;
				}
				
				
				this.axios.get(`${this.IP}/register`, {
					params:{
						code: this.register_yzm,
						telephone: this.register_telephone,
						password: this.register_password
					}
				}).then(res => {
					this.$toast.showMessage(res.data.result);
					if(res.data.result.includes('成功')){
						this.setStorage("token",res.data.token);
						setTimeout(()=>{
							this.$router.push('/firstLogin');
						},3000)
					}
				}).catch(error => {
					// 处理错误  
					console.error('请求出错：', error);
				});;
			},
			toggleVCode(){
				if(this.confirm_btn_1==false){
					this.$toast.showMessage("请先勾选愿意遵守用户协议~");
					return;
				}
				if(this.login_account.trim()==''){
					this.$toast.showMessage("请填写您的登录手机号~");
					return;
				}
				if(this.login_password.trim()==''){
					this.$toast.showMessage("请填写您的登录密码~");
					return;
				}
				if(this.login_account.trim().length!=11){
					this.$toast.showMessage("请填写正确的11位大陆手机号~");
					return;
				}
				
				this.isShow = !this.isShow;
			},
			login2(){
				
				this.isShow = false;
				this.axios.get(`${this.IP}/login`, {
					params:{
						account: this.login_account,
						password: this.login_password
					}
				}).then(res => {
					
					this.$toast.showMessage(res.data.result);
					if(res.data.result.includes('成功')){
						this.setStorage("token",res.data.data.token);
						
						if(this.remember_password){
							let en_psw = CryptoJS.AES.encrypt(this.login_password, "20240426");
							 let en_acc = CryptoJS.AES.encrypt(this.login_account, "20240426");
							  localStorage.setItem('remember_password', en_psw);
							  localStorage.setItem('remember_account', en_acc);
						}else{
							if(localStorage.getItem('remember_password') != null){
								localStorage.removeItem('remember_password');
							}
							if(localStorage.getItem('remember_account') != null){
								localStorage.removeItem('remember_account');
							}
						}
						
						
						setTimeout(()=>{
							this.$router.push('/index');
						},3000)
					}
				}).catch(error => {
					// 处理错误  
					console.error('请求出错：', error);
				});;
			},
			convertToImage(captcha) {
				let that = this;
			    // 创建一个canvas元素  
			    const canvas = document.createElement('canvas');
			    const ctx = canvas.getContext('2d');
			
			    // 设置canvas的尺寸  
			    const width = 70;
			    const height = 15;
			    canvas.width = width;
			    canvas.height = height;
			
			    // Clear the canvas
			    ctx.clearRect(0, 0, width, height);
			
			    // 绘制干扰线  
			    function drawLine() {
			        ctx.beginPath();
			        ctx.moveTo(Math.random() * width, Math.random() * height);
			        ctx.lineTo(Math.random() * width, Math.random() * height);
			        ctx.strokeStyle = that.getRandomColor(); // 设置线条颜色和透明度  
			        ctx.stroke();
			    }
			
			    // 绘制多条干扰线  
			    for (let i = 0; i < 5; i++) { // 可以根据需要调整干扰线的数量  
			        drawLine();
			    }
			
			    // 设置字体样式  
			    ctx.font = '14px Arial';
			    ctx.textAlign = 'center'; // 文本居中  
			    ctx.textBaseline = 'middle'; // 文本垂直居中  
			
			    // 在canvas上绘制验证码文本  
			    for (let i = 0; i < captcha.length; i++) {
			        const x = (i + 0.5) * (width / captcha.length); // Spread characters evenly
			        const y = height / 2;
			        ctx.fillStyle = that.getRandomColor(); // Set random color
			        ctx.fillText(captcha[i], x, y);
			    }
			
			    // 将canvas内容转换为Base64编码的图片  
			    const dataURL = canvas.toDataURL('image/png');
			
			    return dataURL;
			},
			getRandomColor() {
			    const r = Math.floor(Math.random() * 256);
			    const g = Math.floor(Math.random() * 256);
			    const b = Math.floor(Math.random() * 256);
			    return `rgb(${r}, ${g}, ${b})`;
			},
			goto(e){
				this.$refs.mySwiper.swiperInstance.activeIndex=e;
				this.$refs.mySwiper.swiperInstance.update();
			},
			toggle_eye(){
				if(this.eye_state=='眼睛'){
					this.eye_state='眼睛_隐藏';
					this.hide_type="text";
				}else{
					this.eye_state='眼睛';
					this.hide_type="password";
				}
			},
			
		},
		// 在组件创建时获取初始的验证码图片（如果需要）  
		created() {
			this.fetchCaptcha();
		},
	}
</script>

<style scoped>
	.logo_container {
		margin-top: 15vw;
		display: flex;
		flex-direction: row;
		justify-content: center;
	}

	.logo {
		width: 512px;
		height: 512px;
	}

	.index .context {
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		flex-wrap: wrap;
	}

	.index .context div:nth-child(1) {
		font-size: 40px;
		font-weight: bold;
		padding: 3vw;
	}

	.index .context div:nth-child(2) {
		font-size: 24px;
		padding: 3vw;
	}

	.index .select {
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
	}

	.index .select button {
		width: 80vw;
		border-radius: 20px;
		background: #ffffff;
		font-size: 28px;
		margin: 2vw;
		padding: 3vw;
	}

	.index .select button:nth-child(1) {
		background: linear-gradient(to right, #f9d24f, #ffdc50);
	}

	.login_container {
		display: flex;
		flex-direction: column;
		justify-content: center;
		padding: 2vw;
	}

	.login_inputs {
		margin: 10vw 0vw 3vw 0vw;
		display: flex;
		flex-direction: column;
		justify-content: center;
	}

	.login_password_container {
		margin-top: 5vw !important;
		display: flex;
		flex-direction: row;
		justify-content: flex-start;
		align-items: center;
	}

	.login_password_container input {
		flex: 1;
	}

	.login_password_container img {
		width: 48px;
	}

	.login_inputs>input,
	.login_inputs>div {
		padding: 3vw;
		margin: 1vw;
		border: 5px solid #f6f6f6;
		border-radius: 10px;
	}

	input {
		font-size: 36px;
	}

	.login_buttons button {
		width: 80vw;
		border-radius: 20px;
		background: #ffffff;
		font-size: 28px;
		margin: 2vw;
		padding: 3vw;
	}

	.login_buttons button:nth-child(1) {
		background: linear-gradient(to right, #f9d24f, #ffdc50);
	}

	.card {
		margin-top: 10vw;
	}

	.extra_top_container,
	.extra_bottom_container {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 1vw;
	}

	.yzm {
		display: flex;
		flex-direction: row;
		height: 10vw;
	}
	.yzm input{
		width: 50vw !important;
		height: 10vw !important;
	}
	.yzm_right_box{
		width: 60vw;
		height: 10vw;
		position: relative;
	}
	.yzm_right_box img{
		width: 100%;
		height: 100%;
	}
	.yzm_right_box div{
		position: absolute;
		right:-10vw;
		bottom:-10vw;
		min-width:30vw;
		font-size:24px;
	}


	.noclear {
		margin-left: 57vw;
		margin-bottom: 2vw;
		font-size: 2vw;
		color: #06007c;
	}
</style>